package com.CGFrame.struts.action.categorySet;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.CGFrame.struts.POJOs.Category;
import com.CGFrame.struts.POJOs.Company;
import com.CGFrame.struts.bean.ProjectOperate;
import com.CGFrame.struts.bean.ProjectOperateFactory;
import com.CGFrame.struts.bean.log.LogHistoryBean;

public class ModifyAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
	//	System.out.println("Modify Action!!!!");
		
		String name=request.getParameter("categoryName");
		String ename=request.getParameter("categoryEname");
		String cateId=request.getParameter("categoryId");
		String type=request.getParameter("categoryType");
		
		if(name==null){
			System.out.println("cateName is null");
		}
		if(ename==null){
			System.out.println("cateEName is null");
		}
		if(cateId==null){
			System.out.println("cateId is null");
		}
		if(type==null){
			System.out.println("type is null");
		}
		
		ProjectOperate pop = ProjectOperateFactory.getprojectOperate();
		HttpSession session = request.getSession();
		String companyId = (String)session.getAttribute("CompanyID");
		Company c = (Company)pop.UniqueQuery("Company", "companyId,"+companyId);
		
		if(name=="" || ename==""){
			request.setAttribute( "categories", c.getCategories() );
			request.setAttribute("catenull", "name or englishname can not be null!");
			return mapping.findForward("queryCategory");
		}
		
		
		List categorys=pop.Query("Category", null,null,null);
		for(Iterator iter=categorys.iterator();iter.hasNext();){
			Category cat=(Category)iter.next();
			if(cat.getCategoryName()==name || cat.getCategoryEnglishName()==ename || cat.getCategoryType()==type){
				request.setAttribute( "categories", c.getCategories() );
				request.setAttribute("catedup", "duplicated category name!");
				return mapping.findForward("queryCategory");
			}
		}
		
		Category cate=(Category)pop.UniqueQuery("Category", "categoryId,"+cateId);
		cate.setCategoryEnglishName(ename);
		cate.setCategoryName(name);
		cate.setCategoryType(type);
		cate.setCompany(c);
		pop.saveObject(cate);
		
		LogHistoryBean logBean = new LogHistoryBean();
		String regUserId = (String)request.getSession().getAttribute("RegUserID");
		logBean.saveByReguserId(regUserId, LogHistoryBean.MODIFY,null, "Category", cate.getCategoryId() );
		
		request.setAttribute( "categories", c.getCategories() );
		return mapping.findForward("queryCategory");
	}
}
